package com.kaili.basic.controller.web.v1;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.BaseEmployeeAddOrUpdateDto;
import com.kaili.basic.pojo.dto.BaseEmployeeQueryDto;
import com.kaili.basic.pojo.dto.BaseEmployeeUpdatePasswordDto;
import com.kaili.basic.pojo.dto.BaseUserUpdateBaseRolesDto;
import com.kaili.basic.pojo.entity.BaseCompany;
import com.kaili.basic.service.BaseEmployeeService;
import com.kaili.basic.service.BaseUserService;
import com.kaili.basic.service.BasicSiteService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.entity.BaseEmployee;
import com.kaili.common.entity.BaseUser;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.tenant.DbContextHolder;
import com.kaili.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by rzh on 18-5-8.
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Api(tags = "员工管理", description = "员工管理相关API")
public class BaseEmployeeController {
    @Autowired
    private BaseEmployeeService baseEmployeeService;

    @Autowired
    private BasicSiteService basicSiteService;

    Logger log = LoggerFactory.getLogger(BaseEmployeeController.class);


    @ApiOperation(value = "查询员工", notes = "分页查员工")
    @GetMapping("baseEmployee")
    public Page<BaseEmployee> getCompany(@ModelAttribute BaseEmployeeQueryDto baseEmployeeQueryDto) throws RestException {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setPage(baseEmployeeQueryDto.getPage());
        baseEmployee.setPageSize(baseEmployeeQueryDto.getPageSize());
        baseEmployee.setSiteId(baseEmployeeQueryDto.getSiteId());
        baseEmployee.setRid(baseEmployeeQueryDto.getRid());
        baseEmployee.setEmployeeName(baseEmployeeQueryDto.getEmployeeName());
        baseEmployee.setEmployeeCode(baseEmployeeQueryDto.getEmployeeCode());
        if (LoginDetailUtils.getSiteId() != 1)
            baseEmployee.setSiteId(LoginDetailUtils.getSiteId());
        return baseEmployeeService.selectByMap(new Page<BaseEmployee>(baseEmployee.getPage(), baseEmployee.getPageSize()), baseEmployee);
    }


    @ApiOperation(value = "导出员工", notes = "导出员工")
    @GetMapping("baseEmployeeExport")
    public void exportCompany(@ModelAttribute BaseEmployeeQueryDto baseEmployeeQueryDto, HttpServletResponse response) throws RestException {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setPage(baseEmployeeQueryDto.getPage());
        baseEmployee.setPageSize(baseEmployeeQueryDto.getPageSize());
        baseEmployee.setSiteId(baseEmployeeQueryDto.getSiteId());
        baseEmployee.setRid(baseEmployeeQueryDto.getRid());
        baseEmployee.setEmployeeName(baseEmployeeQueryDto.getEmployeeName());
        baseEmployee.setEmployeeCode(baseEmployeeQueryDto.getEmployeeCode());
        if (LoginDetailUtils.getSiteId() != 1)
            baseEmployee.setSiteId(LoginDetailUtils.getSiteId());
        try{
            ExcelUtil.exportExcel(baseEmployeeService.exportByMap(baseEmployee),"用户管理","用户管理",BaseEmployee.class,"用户管理"+UUIDUtil.getUUId()+".xls",response);
        }catch (RestException e){
            log.error("用户管理导出异常"+e.getMessage());
        }
        ;
    }

    @ApiOperation(value = "查询员工", notes = "模糊查询员工")
    @GetMapping("baseEmployee/page/{par}")
    public Page<BaseEmployee> selectByPar(@PathVariable String par) throws RestException {
        Integer par1 = null;
        if (LoginDetailUtils.getSiteId() != 1)
            par1 = LoginDetailUtils.getSiteId();
        return baseEmployeeService.selectByPar(new Page<BaseEmployee>(0, 50), par, par1);
    }

    @ApiOperation(value = "查询员工", notes = "根据id查询员工")
    @GetMapping("baseEmployee/{id}")
    public BaseEmployee getById(@PathVariable Integer id) throws RestException {
        return baseEmployeeService.selectById(id);
    }

    @ApiOperation(value = "新增或修改", notes = "新增或修改员工")
    @PostMapping("baseEmployee")
    public RestStatus insertOrUpdate(@Validated @RequestBody BaseEmployeeAddOrUpdateDto baseEmployeeAddOrUpdateDto) {
        BaseEmployee baseEmployee = new BaseEmployee();
        baseEmployee.setEmployeeCode(baseEmployeeAddOrUpdateDto.getEmployeeCode());
        baseEmployee.setEmployeeName(baseEmployeeAddOrUpdateDto.getEmployeeName());
        baseEmployee.setEmployeeRealName(baseEmployeeAddOrUpdateDto.getEmployeeRealName());
        baseEmployee.setMail(baseEmployeeAddOrUpdateDto.getMail());
        baseEmployee.setSiteId(baseEmployeeAddOrUpdateDto.getDeptId());
        baseEmployee.setRid(baseEmployeeAddOrUpdateDto.getRid());
        baseEmployee.setEmployeeType(baseEmployeeAddOrUpdateDto.getEmployeeType());
        baseEmployee.setShipper(baseEmployeeAddOrUpdateDto.getShipper());
        baseEmployee.setDepot(baseEmployeeAddOrUpdateDto.getDepot());
        baseEmployee.setPhone(baseEmployeeAddOrUpdateDto.getPhone());
        baseEmployee.setLandPhone(baseEmployeeAddOrUpdateDto.getLandPhone());
        baseEmployee.setPassword(baseEmployeeAddOrUpdateDto.getPassword());
        baseEmployee.setId(baseEmployeeAddOrUpdateDto.getId());
        baseEmployee.setCompanyId(baseEmployeeAddOrUpdateDto.getCompanyId());
        baseEmployee.setPinyin(PinYinUtil.toPinYin(baseEmployee.getEmployeeName()));
        baseEmployee.setRemark(baseEmployeeAddOrUpdateDto.getRemark());
        if (baseEmployee.getPassword() != null && baseEmployee.getPassword().length() <= 10 && !"".equals(baseEmployee.getPassword())) {
            String pwd = baseEmployee.getPassword();//密码
            String npwd = baseEmployee.getPassword();//用来循环的密码；
            String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
            baseEmployee.setPassword(encode);
        }
        if (baseEmployee.getId() != null) {
            baseEmployee.setSiteName(null);
            baseEmployee.setrName(null);
            baseEmployee.setCreatedName(null);
            baseEmployee.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
            baseEmployee.setModifyTime(new Date());
        } else {
            baseEmployee.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
            baseEmployee.setCreateTime(new Date());
            baseEmployee.setLoadTimes(0);
        }

        baseEmployeeService.insertOrUpdate(baseEmployee);


        if (baseEmployee.getId() != null) {
            return CommonStatus.UPDATE_OK;
        }
        return CommonStatus.ADD_OK;
    }

    //修改密码
    @ApiOperation(value = "修改密码", notes = "根据Id修改密码")
    @PutMapping("baseEmployee")
    public RestStatus updatePassword(@Validated @RequestBody BaseEmployeeUpdatePasswordDto baseEmployeeAddOrUpdateDto) {
        Map<String,Object> params = new HashMap<String,Object>();
        if (baseEmployeeAddOrUpdateDto.getPassword() != null && baseEmployeeAddOrUpdateDto.getPassword().length() <= 10 && !"".equals(baseEmployeeAddOrUpdateDto.getPassword())){
            String pwd = baseEmployeeAddOrUpdateDto.getPassword();//密码
            String npwd = baseEmployeeAddOrUpdateDto.getPassword();//用来循环的密码；
            String encode = hexpwd(pwd, npwd);//加密后16进制的密码;
            params.put("password",encode);
        }
        params.put("id",baseEmployeeAddOrUpdateDto.getId());

        baseEmployeeService.updatePasswordById(params);
        return CommonStatus.UPDATE_OK;
    }

    @ApiOperation(value = "删除", notes = "根据Id删除员工")
    @DeleteMapping("baseEmployee/{id}")
    public RestStatus delete(@PathVariable Integer id) {
        baseEmployeeService.deleteById(id);
        return CommonStatus.DELETE_OK;
    }

    @ApiOperation(value = "获取Code", notes = "获取员工Code")
    @GetMapping("baseEmployee/code")
    public Map getCode() throws RestException {
        String siteCode = basicSiteService.getBySiteId(getById(LoginDetailUtils.getCurrentEmployeeId()).getSiteId().longValue()).getSiteCode();
        String code = baseEmployeeService.getCode();
        Map map = new HashMap();
        map.put("siteCode", siteCode);
        map.put("code", code);
        return map;
    }


    public String hexpwd(String pwd, String npwd) {
        String salt = UUID.randomUUID().toString().substring(0, 6);
        System.out.println(SHA256Util.getSHA256StrJava("G1" + salt + pwd).length());//G1+随机数+密码进行SHA256运算
        Random random = new Random();
        int cycletimes = (int) (random.nextInt(100)) + 100;//后随机数范围变成[ 100~999）；循环次数
        System.out.println(cycletimes);
        String sh256 = "";
        sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
        for (int i = 0; i <= cycletimes; i++) {
            sh256 = SHA256Util.getSHA256StrJava("G1" + salt + pwd + sh256);//G1+随机数+密码进行SHA256运算 循环多少次循环的次数是随机生成的
            sh256 = sh256;
            //sh256=SHA256Util.getSHA256StrJava("G1"+cd+"123456");
            //System.out.println(sh256);
        }
        System.out.println(sh256);
        String hex = HexStringUtils.toHex("G1" + salt + cycletimes + sh256);//16进制字符串
        System.out.println("16进制字符串存数据库" + hex);
        return hex;
    }



}
